﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Vds2465Parser
{
	internal static class GenParse_UserData_AsciiBytes_Address
	{
		#region constants

		private const byte RelativeAddressByteFlag = 0x1B;

		#endregion constants

		#region internal methods

		internal static byte[] GenerateBytes(byte userDataType, byte[] asciiAddressBytes, bool relativeAddressFlag, int maxNrOfChars)
		{
			if (relativeAddressFlag)
			{
				// prepend the special byte
				if (asciiAddressBytes != null)
				{
					byte[] asciiBytes_WithRelativeAddress = new byte[asciiAddressBytes.Length + 1];
					asciiBytes_WithRelativeAddress[0] = RelativeAddressByteFlag;
					for (int index = 0; index < asciiAddressBytes.Length; index++)
					{
						asciiBytes_WithRelativeAddress[index + 1] = asciiAddressBytes[index];
					}

					return GenParse_UserData_AsciiBytes.GenerateBytes(userDataType, asciiBytes_WithRelativeAddress, maxNrOfChars);
				}

				// TODO handle error - asciiBytes equals null
			}

			// RelativeAddress is false, no need for the special byte
			return GenParse_UserData_AsciiBytes.GenerateBytes(userDataType, asciiAddressBytes, maxNrOfChars);			
		}

		internal static bool ParseBytes(byte[] userDataBytes, byte userDataType, out byte[] asciiAddressBytes, out bool relativeAddressFlag, out int consumedBytes)
		{
			asciiAddressBytes = null;
			relativeAddressFlag = false;
			consumedBytes = 0;

			byte[] tmpAsciiAddressBytes;
			bool bRetVal = GenParse_UserData_AsciiBytes.ParseBytes(userDataBytes, userDataType, out tmpAsciiAddressBytes, out consumedBytes);
			if (bRetVal)
			{
				asciiAddressBytes = tmpAsciiAddressBytes;
				relativeAddressFlag = false;
				if ((tmpAsciiAddressBytes != null) && (tmpAsciiAddressBytes.Length > 0))
				{
					if (tmpAsciiAddressBytes[0] == RelativeAddressByteFlag)
					{
						relativeAddressFlag = true;

						// remove the special byte
						asciiAddressBytes = new byte[tmpAsciiAddressBytes.Length - 1];
						for (int index = 0; index < asciiAddressBytes.Length; index++)
						{
							asciiAddressBytes[index] = tmpAsciiAddressBytes[index + 1];
						}
					}
				}
			}

			return bRetVal;
		}

		#endregion internal methods
	}
}
